package com.ja.openchat.ui.chat;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;

import androidx.annotation.StringRes;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Reader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.audio.AudioPlayManager;
import com.ja.openchat.ui.chat.audio.IAudioPlayListener;
import com.ja.openchat.ui.chat.listener.OnClearMessageListener;
import com.ja.openchat.ui.chat.listener.OnDeleteMessageListener;
import com.ja.openchat.ui.chat.listener.OnMessageDeliverListener;
import com.ja.openchat.ui.chat.listener.OnMessageUpdateListener;
import com.ja.openchat.ui.chat.listener.OnRecallMessageListener;
import com.ja.openchat.ui.chat.listener.OnReceiveMessageListener;
import com.ja.openchat.ui.chat.listener.OnSendMessageListener;
import com.ja.openchat.ui.chat.listener.OperateResult;
import com.zy.openchat.App;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.FormatTextInfo;
import com.zy.openchat.core.model.message.LocationData;
import com.zy.openchat.core.model.message.MessageContent;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.message.ReplyMarkupInfo;
import com.zy.openchat.core.model.message.TextEntity;
import com.zy.openchat.core.model.message.UiMessage;
import com.zy.openchat.core.model.photo.PhotoInfo;
import com.zy.openchat.core.model.sticker.StickerInfo;
import com.zy.openchat.core.model.user.OrgUserInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.video.VideoInfo;
import com.zy.openchat.util.UIUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.goldze.mvvmhabit.base.BaseActivity;

public class MessageViewModel extends ViewModel implements OnReceiveMessageListener,
        OnSendMessageListener,
        OnDeleteMessageListener,
        OnRecallMessageListener,
        OnMessageUpdateListener,
        OnMessageDeliverListener,
        OnClearMessageListener {
    private MutableLiveData<UiMessage> messageLiveData;
    private MutableLiveData<UiMessage> messageUpdateLiveData;
    private MutableLiveData<Map<String, String>> mediaUploadedLiveData;
    private MutableLiveData<Pair<Long,String>> groupSubTitleLiveData;
    private MutableLiveData<Map<String, Long>> messageDeliverLiveData;
    private MutableLiveData<SuperGroupInfo> groupInfoLiveData;

    public MutableLiveData<String> getAnnouncementTitle() {
        if (announcementTitle == null) {
            announcementTitle = new MutableLiveData<>();
        }
        return announcementTitle;
    }
    private MutableLiveData<String> announcementTitle;
    private MessageInfo toPlayAudioMessage;

    public MessageViewModel() {

    }

    @Override
    protected void onCleared() {

    }

    @Override
    public void onReceiveMessage(List<MessageInfo> messages, boolean hasMore) {
        if (messageLiveData != null && messages != null) {
            for (MessageInfo msg : messages) {
                postNewMessage(new UiMessage(msg));
            }
        }
    }

    public MutableLiveData<SuperGroupInfo> groupInfoLiveData() {
        if (groupInfoLiveData == null) {
            groupInfoLiveData = new MutableLiveData<>();
        }
        return groupInfoLiveData;
    }

    public MutableLiveData<UiMessage> messageLiveData() {
        if (messageLiveData == null) {
            messageLiveData = new MutableLiveData<>();
        }
        return messageLiveData;
    }

    public MutableLiveData<UiMessage> messageUpdateLiveData() {
        if (messageUpdateLiveData == null) {
            messageUpdateLiveData = new MutableLiveData<>();
        }
        return messageUpdateLiveData;
    }

    public MutableLiveData<Map<String, String>> mediaUpdateLiveData() {
        if (mediaUploadedLiveData == null) {
            mediaUploadedLiveData = new MutableLiveData<>();
        }
        return mediaUploadedLiveData;
    }

    public MutableLiveData<Pair<Long,String>> groupSubTitleLiveData() {
        if (groupSubTitleLiveData == null) {
            groupSubTitleLiveData = new MutableLiveData<>();
        }
        return groupSubTitleLiveData;
    }

    public MutableLiveData<Map<String, Long>> messageDeliverLiveData() {
        if (messageDeliverLiveData == null) {
            messageDeliverLiveData = new MutableLiveData<>();
        }
        return messageDeliverLiveData;
    }


    public boolean canEditGroupSetting(SuperGroupInfo super_groupInfo) {
        if (super_groupInfo != null && super_groupInfo.status != null) {
            switch (super_groupInfo.status.getMemberState()) {
                case GroupMemberState_Administrator:
                    //管理员
                    return true;
                case GroupMemberState_Creator:
                    //创建者
                    if (super_groupInfo.status.is_member) {
                        return true;
                    }
                    break;
                case GroupMemberState_Left:
                    //不在群组
                    break;
                case GroupMemberState_Member:
                    //普通成员
                    break;
                case GroupMemberState_Banned:
                    //被禁用
                    break;
                case GroupMemberState_Restricted:
                    //被禁言
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    @Override
    public void onRecallMessage(MessageInfo message) {
        if (message != null) {
            UiMessage uiMessage = new UiMessage(message);
            if (toPlayAudioMessage != null && toPlayAudioMessage.id == message.id) {
                stopPlayAudio();
            }
            postMessageUpdate(uiMessage);
        }
    }

    // TODO 可优化成moveTo
    public void resendMessage(ChatInfo conversation,MessageInfo message) {
//        deleteMessage(message);
//        sendMessage(message.conversation, message.content);
        List<Long> messageIds = new ArrayList<>();
        messageIds.add(message.id);
        TelegramManager.getTelegramManager().resendMessages(ActivityUtils.getTopActivity(),conversation.id, messageIds,new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                showErrorTip(getString(R.string.request_error));
            }
        });

    }

    public void recallMessage(MessageInfo message) {
        deleteOrRevoke(message, true);
    }

    @Override
    public void onDeleteMessage(MessageInfo message) {
        deleteMessage(message);
    }

    /**
     * 删除消息
     *
     * @param message
     */
    public void deleteMessage(MessageInfo message) {
        deleteOrRevoke(message, false);
    }

    public void showProgress(){
        if(ActivityUtils.getTopActivity()!=null && ActivityUtils.getTopActivity() instanceof BaseActivity){
            ((BaseActivity)ActivityUtils.getTopActivity()).showProgress();
        }
    }

    public void hideProgress(){
        if(ActivityUtils.getTopActivity()!=null && ActivityUtils.getTopActivity() instanceof BaseActivity){
            ((BaseActivity)ActivityUtils.getTopActivity()).hideProgress();
        }
    }


    public void addSticker(String remoteFildId){
        showProgress();
        TelegramManager.getTelegramManager().addFavoriteSticker(ActivityUtils.getTopActivity(), remoteFildId, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }else if(obj!=null&&obj.ok){
                    ToastUtils.showShort(ActivityUtils.getTopActivity().getString(R.string.emoji_added));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void removeSticker(StickerInfo stickerInfo){
        showProgress();
        TelegramManager.getTelegramManager().removeFavoriteSticker(ActivityUtils.getTopActivity(), String.valueOf(stickerInfo.getRemoteAnimationFileId()), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }else if(obj!=null&&obj.ok){
                    ToastUtils.showShort(ActivityUtils.getTopActivity().getString(R.string.emote_canceled));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void deleteOrRevoke(MessageInfo message,boolean isRevoke){
        showProgress();
        List<Long> ids = new ArrayList<>();
        ids.add(message.id);
        if(TelegramManager.getTelegramManager().getTgData().chatInfo(message.chat_id).isGroup()){
            TelegramManager.getTelegramManager().deleteSuperGroupMessages(ActivityUtils.getTopActivity(),message.chat_id, ids, isRevoke, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    if (obj!=null&&!obj.ok) {
                        showErrorTip(obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }else{
            TelegramManager.getTelegramManager().deleteP2pMessages(ActivityUtils.getTopActivity(),message.chat_id, ids, isRevoke, new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    hideProgress();
                    if (obj!=null&&!obj.ok) {
                        showErrorTip(obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    hideProgress();
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }
    }

    private String getString(@StringRes int resId){
        return ActivityUtils.getTopActivity().getString(resId);
    }

    private void showErrorTip(String errorMsg){
        ToastUtils.showShort(errorMsg);
    }


    public void playAudioMessage(UiMessage message) {
        if (message == null || message.message.messageType!= TelegramManager.MessageType.MessageType_Audio) {
            return;
        }

        if (toPlayAudioMessage != null && toPlayAudioMessage.equals(message.message)) {
            AudioPlayManager.getInstance().stopPlay();
            toPlayAudioMessage = null;
            return;
        }

        toPlayAudioMessage = message.message;
        File file = new File(message.message.audioLocalPath());

        if (file == null) {
            return;
        }
        if (file.exists()) {
            playAudio(message, file);
        } else {
            Log.e("ChatInfoViewHolder", "audio not exist");
        }
    }

    public void playVoiceMessage(UiMessage message) {
        if (message == null || message.message.messageType!= TelegramManager.MessageType.MessageType_Voice_Note) {
            return;
        }

        if (toPlayAudioMessage != null && toPlayAudioMessage.equals(message.message)) {
            AudioPlayManager.getInstance().stopPlay();
            toPlayAudioMessage = null;
            return;
        }

        toPlayAudioMessage = message.message;
        File file = new File(message.message.voiceLocalPath());

        if (file == null) {
            return;
        }
        if (file.exists()) {
            playAudio(message, file);
        } else {
            Log.e("ChatInfoViewHolder", "voice not exist");
        }
    }

    public void stopPlayAudio() {
        AudioPlayManager.getInstance().stopPlay();
    }

    public void sendMessage(ChatInfo conversation, List<String> toUsers, MessageContent content) {

    }

    public MutableLiveData<OperateResult<Boolean>> sendMessageEx(MessageInfo message) {

        // TODO
        return null;
    }

    public void sendMessage(MessageInfo message) {
        // the call back would be called on the ui thread
//        message.sender = ChatManager.Instance().getUserId();
//        ChatManager.Instance().sendMessage(message, null);
    }

    public void sendTextMsg(ChatInfo conversation, String txtContent) {
        sendTextMsg(conversation,txtContent,null);
    }

    public void sendTextMsg(ChatInfo conversation, String txtContent, List<TextEntity> textEntities) {
        sendTextMsg(conversation,txtContent,0,textEntities);
    }

    public void sendTextMsg(ChatInfo conversation, String txtContent,long replyMessageId,List<TextEntity> textEntities) {
        sendTextMsg(conversation,txtContent,replyMessageId,textEntities,-1);
    }

    public void sendTextMsg(ChatInfo conversation, String txtContent,long replyMessageId,List<TextEntity> textEntities,int countDown) {
        if(!canSendTextMsg(conversation,txtContent)){
            return;
        }
        if(replyMessageId>0){
            TelegramManager.getTelegramManager().sendTextMessage(ActivityUtils.getTopActivity(),conversation.id, txtContent, replyMessageId,textEntities,countDown,conversation.isSuperGroup()?canEditGroupSetting():false,new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    if (obj!=null&&!obj.ok) {
                        showErrorTip(obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }else{
            TelegramManager.getTelegramManager().sendTextMessage(ActivityUtils.getTopActivity(),conversation.id, txtContent,0,textEntities, countDown,conversation.isSuperGroup()?canEditGroupSetting():false,new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    if (obj!=null&&!obj.ok) {
                        showErrorTip(obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }
    }

    public boolean canSendTextMsg(ChatInfo chatInfo,String content){
        if(chatInfo==null||!chatInfo.isGroup()){
            return true;
        }
        if(canEditGroupSetting()){
            return true;
        }
        if(chatInfo!=null&&chatInfo.permissions!=null&&chatInfo.permissions.banSendWebLink){
            String[] array = linkString(content);
            if(isLinkString(content)){
                showErrorTip(ActivityUtils.getTopActivity().getString(R.string.forbidden_send_link));
                return false;
            }
        }
        if(chatInfo!=null&&chatInfo.permissions!=null&&chatInfo.permissions.keywords!=null&&chatInfo.permissions.keywords.size()>0){
            List<String> keywords = chatInfo.permissions.keywords;
            for(String keyword:keywords){
                if(content.contains(keyword)){
                    if(chatInfo.permissions.kickWhoSendKeyword){
                        TelegramManager.getTelegramManager().kickWhoSendKeyword(ActivityUtils.getTopActivity(), chatInfo.id, new TgResultBlock<TgResponse>() {
                            @Override
                            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {

                            }

                            @Override
                            public void onTimeout(Map<String, Object> request) {

                            }
                        });
                    }
                    showErrorTip(String.format("%s：%s",App.getInstanse().getString(R.string.group_prohibits_words),keyword));
                    return false;
                }
            }
        }
        return true;
    }

    public static boolean isLinkString(String urls){
        boolean isurl = false;
        String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";//设置正则表达式

        Pattern pat = Pattern.compile(regex.trim());//对比
        Matcher mat = pat.matcher(urls.trim());
        isurl = mat.matches();//判断是否匹配
        if (isurl) {
            isurl = true;
        }
        return isurl;
    }

    public static String[] linkString(String str){
        if(TextUtils.isEmpty(str)){
            return null;
        }
        Matcher m = Pattern.compile("(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)").matcher(str);
        String[] url = new String[str.length()/5];
        int count = 0;
        while(m.find()){
            url[count] = m.group();
            count++;
        }
        return url;
    }

    public boolean canSendMediaMsg(ChatInfo chatInfo){
        if(chatInfo==null||!chatInfo.isGroup()){
            return true;
        }
        if(canEditGroupSetting()){
            return true;
        }
        if(chatInfo!=null&&chatInfo.permissions!=null){
            if(!chatInfo.permissions.can_send_media_messages){
                showErrorTip(ActivityUtils.getTopActivity().getString(R.string.forbidden_send_media));
            }
            return chatInfo.permissions.can_send_media_messages;
        }
        return true;
    }



    public boolean canSendQrImg(ChatInfo chatInfo,Bitmap bitmap){
        if(chatInfo==null||!chatInfo.isGroup()){
            return true;
        }
        if(canEditGroupSetting()){
            return true;
        }
        if(chatInfo!=null&&chatInfo.permissions!=null&&chatInfo.permissions.banSendQRcode){
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int[] pixels = new int[width * height];
            bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
            RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
            Reader reader = new QRCodeReader();
            Result result = null;
            try {
                result = reader.decode(binaryBitmap);
            } catch (NotFoundException | ChecksumException | FormatException e) {
                e.printStackTrace();
            }
            if(result!=null&&!TextUtils.isEmpty(result.getText())){
                showErrorTip(getString(R.string.group_ban_qr));
                return false;
            }
        }
        return true;
    }

    public void sendImgMsg(ChatInfo conversation,String localPath,  Bitmap bitmap,int width, int height) {
        sendImgMsg(conversation,null,localPath,bitmap,width,height);
    }

    public void sendImgMsg(ChatInfo conversation,String remark, String localPath,  Bitmap bitmap,int width, int height) {
        if(TextUtils.isEmpty(localPath)){
            return;
        }
        if(!canSendMediaMsg(conversation)){
            return;
        }
        if(!canSendQrImg(conversation,bitmap)){

            return;
        }
        TgResultBlock<TgResponse> response = new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                showErrorTip(getString(R.string.request_error));
            }
        };

        if(localPath.endsWith(".gif")||localPath.endsWith(".GIF")){
            TelegramManager.getTelegramManager().sendGifMessage(ActivityUtils.getTopActivity(),conversation.id, localPath, width, height, getBurnAfterCountDown(),response);

        }else{
            ArrayList<Long> group_uers = conversation.group_uers;
            if(!TextUtils.isEmpty(remark)){
                Pair<String, ReplyMarkupInfo> pair = TelegramManager.getTelegramManager().getReplyMarkupByText(remark);
                if(pair==null||!TextUtils.isEmpty(pair.first)){
                    if(group_uers != null && group_uers.size() > 0){
                        for (int i = 0 ; i < group_uers.size();i++){
                            TelegramManager.getTelegramManager().sendPhotoMessage(ActivityUtils.getTopActivity()
                                    , group_uers.get(i)
                                    , TelegramManager.getTelegramManager().buildLocalPhotoMessageContent(localPath, width, height,new FormatTextInfo(remark))
                                    , getBurnAfterCountDown(), null, response);
                        }
                    }else{
                        TelegramManager.getTelegramManager().sendPhotoMessage(ActivityUtils.getTopActivity()
                                , conversation.id
                                , TelegramManager.getTelegramManager().buildLocalPhotoMessageContent(localPath, width, height,new FormatTextInfo(remark))
                                , getBurnAfterCountDown(), null, response);
                    }
                    return;

                }else{
                    //图片+按钮组合
                    if(group_uers != null && group_uers.size() > 0){
                        for (int i = 0 ; i < group_uers.size();i++){
                            TelegramManager.getTelegramManager().sendPhotoMessage(ActivityUtils.getTopActivity()
                                    , group_uers.get(i)
                                    , TelegramManager.getTelegramManager().buildLocalPhotoMessageContent(localPath, width, height,null)
                                    , getBurnAfterCountDown(), pair.second, response);
                        }
                    }else{
                        TelegramManager.getTelegramManager().sendPhotoMessage(ActivityUtils.getTopActivity()
                                , conversation.id
                                , TelegramManager.getTelegramManager().buildLocalPhotoMessageContent(localPath, width, height,null)
                                , getBurnAfterCountDown(), pair.second, response);
                    }
                    return;
                }

            }
            if(group_uers != null && group_uers.size() > 0){
                for (int i = 0 ; i < group_uers.size();i++){
                    TelegramManager.getTelegramManager().sendPhotoMessage(ActivityUtils.getTopActivity(),group_uers.get(i), localPath, width, height, getBurnAfterCountDown(),response);
                }
            }else{
                TelegramManager.getTelegramManager().sendPhotoMessage(ActivityUtils.getTopActivity(),conversation.id, localPath, width, height, getBurnAfterCountDown(),response);
            }
            //转换ID
        }

    }

    public void sendContactMsg(ChatInfo conversation, UserInfo userInfo) {

        TelegramManager.getTelegramManager().requestOrgContactInfo(ActivityUtils.getTopActivity(), userInfo.id, new TgResultBlock<OrgUserInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, OrgUserInfo obj) {
                userInfo.raw_first_name = obj.firstName;
                userInfo.raw_last_name = obj.lastName;
                sendContactMsgSecond(conversation,userInfo);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public  void sendContactMsgSecond(ChatInfo conversation, UserInfo userInfo) {
        TelegramManager.getTelegramManager().sendContactMessage(ActivityUtils.getTopActivity(),conversation.id, userInfo,getBurnAfterCountDown(),new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void sendVideoMsg(ChatInfo conversation, String path,long duration,int width, int height) {
        if(!canSendMediaMsg(conversation)){
            return;
        }
        TelegramManager.getTelegramManager().sendVideoMessage(ActivityUtils.getTopActivity(),conversation.id, null, path, width, height, duration,getBurnAfterCountDown(),new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void sendStickerMsg(ChatInfo conversation, StickerInfo stickerInfo) {
        TelegramManager.getTelegramManager().sendStickerGifMessage(ActivityUtils.getTopActivity(),conversation.id, stickerInfo.getRemoteAnimationFileId(), stickerInfo.width, stickerInfo.height,getBurnAfterCountDown(), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void sendAudioFile(ChatInfo conversation, Uri audioPath, int duration) {
        if(!canSendMediaMsg(conversation)){
            return;
        }
        if (audioPath != null) {
            File file = new File(audioPath.getPath());
            if (!file.exists() || file.length() == 0L) {
                ToastUtils.showShort(ActivityUtils.getTopActivity().getString(R.string.failed_send_voice));
                return;
            }
            TelegramManager.getTelegramManager().sendAudioMessage(ActivityUtils.getTopActivity(),conversation.id, file.getAbsolutePath(), duration,getBurnAfterCountDown(),new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    if (obj!=null&&!obj.ok) {
                        showErrorTip(obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }

    }


    public void sendFileMessage(ChatInfo conversation,File file){
        if(!canSendMediaMsg(conversation)){
            return;
        }
        if(file!=null&&file.exists()){
            TelegramManager.getTelegramManager().sendFileMessage(ActivityUtils.getTopActivity(), conversation.id, file.getName(), file.getAbsolutePath(),getBurnAfterCountDown(), new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    if (obj!=null&&!obj.ok) {
                        showErrorTip(obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }
    }

    public void sendLocationMessage(ChatInfo conversation, LocationData locationData) {
        if(locationData!=null){
            TelegramManager.getTelegramManager().sendLocationMessage(ActivityUtils.getTopActivity(), conversation.id, locationData.getLat(), locationData.getLng(),getBurnAfterCountDown(), new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    if (obj!=null&&!obj.ok) {
                        showErrorTip(obj.errString);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    showErrorTip(getString(R.string.request_error));
                }
            });
        }
    }

    private void playAudio(UiMessage message, File file) {
        Uri uri = Uri.fromFile(file);
        AudioPlayManager.getInstance().startPlay(App.getInstanse(), uri, new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1, int lengthoftime) {
                Log.d("uriisPlaying","onStart==="+var1.toString());
                if (uri.equals(var1)) {
                    message.isPlaying = true;
                    postMessageUpdate(message);
                }else{

                }
            }

            @Override
            public void onStop(Uri var1) {
                Log.d("uriisPlaying","onStop==="+var1.toString());
                if (uri.equals(var1)) {
                    message.isPlaying = false;
                    toPlayAudioMessage = null;
                    postMessageUpdate(message);
                }else{

                }
            }

            @Override
            public void onProgress(Uri var1,int  currentPosition,int secendProssed, int totalLenght) {
//                Log.d("uriisPlaying","onProgress==="+var1.toString());
                if (uri.equals(var1)) {
                    message.isPlaying = true;
                    message.currentPosition = currentPosition;
                    message.secendProssed = secendProssed;
                    message.totalLenght = totalLenght;
                    postMessageUpdate(message);
                }else{

                }
            }

            @Override
            public void onComplete(Uri var1) {
                Log.d("uriisPlaying","onComplete==="+var1.toString());
                if (uri.equals(var1)) {
                    message.isPlaying = false;
                    toPlayAudioMessage = null;
                    postMessageUpdate(message);
                }else{

                }
            }
        });
    }

    public File mediaMessageContentFile(MessageInfo message) {

        String dir = null;
        String name = null;
        if (message.messageType!= TelegramManager.MessageType.MessageType_Audio
                ||message.messageType!= TelegramManager.MessageType.MessageType_Voice_Note
                ||message.messageType!= TelegramManager.MessageType.MessageType_Video
                ||message.messageType!= TelegramManager.MessageType.MessageType_Photo) {
            return null;
        }
        MessageContent content = message.content;


        String localPath = null;
        if(message.messageType == TelegramManager.MessageType.MessageType_Audio){
            if(message.content.audio.isAudioDownloaded()){
                localPath = message.content.audio.localAudioPath();
            }
        }else if(message.messageType == TelegramManager.MessageType.MessageType_Voice_Note){
            if(message.content.voice_note.isAudioDownloaded()){
                localPath = message.content.voice_note.localAudioPath();
            }
        }else if(message.messageType == TelegramManager.MessageType.MessageType_Video){
            if(message.content.video.isVideoDownloaded()){
                localPath = message.content.video.localVideoPath();
            }
        }else if(message.messageType == TelegramManager.MessageType.MessageType_Photo){
            if(message.content.photo.previewPhoto().isPhotoDownloaded()){
                localPath = message.content.photo.previewPhoto().photo.local.path;
            }
        }
        if (!TextUtils.isEmpty(localPath)) {
            return new File(localPath);
        }

        if(message.messageType == TelegramManager.MessageType.MessageType_Audio){
            name = System.currentTimeMillis() + ".mp3";
            dir = Constants.userAudioPath();
        }else if(message.messageType == TelegramManager.MessageType.MessageType_Video){
            name = System.currentTimeMillis() + ".mp4";
            dir = Constants.userVideoPath();
        }
        if (TextUtils.isEmpty(dir) || TextUtils.isEmpty(name)) {
            return null;
        }
        return new File(dir, name);
    }

    private void postMessageUpdate(UiMessage message) {
        if (message == null || message.message == null) {
            return;
        }
        if (messageUpdateLiveData != null) {
            UIUtils.postTaskSafely(() -> messageUpdateLiveData.setValue(message));
        }
    }

    private void postNewMessage(UiMessage message) {
        if (message == null || message.message == null) {
            return;
        }
        if (messageLiveData != null) {
            UIUtils.postTaskSafely(() -> messageLiveData.setValue(message));
        }
    }

    @Override
    public void onSendSuccess(MessageInfo message) {
        postMessageUpdate(new UiMessage(message));
    }

    @Override
    public void onSendFail(MessageInfo message, int errorCode) {
        postMessageUpdate(new UiMessage(message));
    }

    @Override
    public void onSendPrepare(MessageInfo message, long savedTime) {
        postNewMessage(new UiMessage(message));
    }

    @Override
    public void onProgress(MessageInfo message, long uploaded, long total) {
        UiMessage uiMessage = new UiMessage(message);
        uiMessage.progress = (int) (uploaded * 100 / total);
        postMessageUpdate(uiMessage);
    }

    @Override
    public void onMediaUpload(MessageInfo message, String remoteUrl) {
        if (mediaUploadedLiveData != null) {
//            Map<String, String> map = new HashMap<>();
//            map.put(((MediaMessageContent) message.content).localPath, remoteUrl);
//            UIUtils.postTaskSafely(() -> mediaUploadedLiveData.setValue(map));
        }
    }

    @Override
    public void onMessageUpdate(MessageInfo message) {
        postNewMessage(new UiMessage(message));
    }

    @Override
    public void onClearMessage(ChatInfo conversation) {

    }

    @Override
    public void onMessageDelivered(Map<String, Long> deliveries) {
        if (messageDeliverLiveData != null) {
            messageDeliverLiveData.postValue(deliveries);
        }
    }

    public int getBurnAfterCountDown(){
//        if(burnAfterAfterReadPosition<0){
//            return -1;
//        }else{
//            return ChooseReadTimeDialog.getSecondByIndex(burnAfterAfterReadPosition);
//        }

        return burnAfterAfterReadSeconds;
    }

    private int burnAfterAfterReadPosition = -1;

    public void setBurnAfterAfterReadSeconds(int burnAfterAfterReadSeconds) {
        this.burnAfterAfterReadSeconds = burnAfterAfterReadSeconds;
    }

    private int burnAfterAfterReadSeconds = -1;

    public int getCurrentProgress() {
        return currentProgress;
    }

    public void setCurrentProgress(int currentProgress) {
        this.currentProgress = currentProgress;
    }

    private int currentProgress = -1;

    public void setBurnAfterReadPosition(int position){
        burnAfterAfterReadPosition = position;
    }

    private SuperGroupInfo superGroupInfo = null;

    public SuperGroupInfo getSuperGroupInfo(){
        return superGroupInfo;
    }

    public boolean isGroupCreator(long userId) {
        if(adminMemberInfos !=null&& adminMemberInfos.size()>0){
            for(GroupMemberInfo memberInfo: adminMemberInfos){
                if(memberInfo.user_id == userId){
                    return memberInfo.status.getMemberState() == TelegramManager.GroupMemberState.GroupMemberState_Creator&&memberInfo.status.is_member;
                }
            }
        }
        return false;
    }

    private List<GroupMemberInfo> adminMemberInfos = null;

    private List<GroupMemberInfo> silenceMemberInfos = null;

    private List<GroupMemberInfo> groupMemberInfos = null;

    public List<GroupMemberInfo> getGroupAdminMembers(){
        return adminMemberInfos;
    }


    public List<GroupMemberInfo> getGroupMembers(){
        return groupMemberInfos;
    }


    public boolean isGroupAdministrator(long userId){
        if(adminMemberInfos !=null&& adminMemberInfos.size()>0){
            for(GroupMemberInfo memberInfo: adminMemberInfos){
                if(memberInfo.user_id == userId){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean isSilenceMember(long userId){
        if(silenceMemberInfos !=null&& silenceMemberInfos.size()>0){
            for(GroupMemberInfo memberInfo: silenceMemberInfos){
                if(memberInfo.user_id == userId){
                    return true;
                }
            }
        }
        return false;
    }

    public void banMemberFromSuperGroup(Context context, ChatInfo chatInfo, UserInfo userInfo, boolean isSilence){
        showProgress();
        TelegramManager.getTelegramManager().banMemberFromSuperGroup(context, chatInfo.id, userInfo.id, isSilence, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void delAllHisMessagesFromSuperGroup(Context context, ChatInfo chatInfo, UserInfo userInfo){
        showProgress();
        TelegramManager.getTelegramManager().delAllHisMessagesFromSuperGroup(context, chatInfo.id, userInfo.id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void loadGroupInfo(Context context,ChatInfo chatInfo){
        if(chatInfo!=null&&chatInfo.isSuperGroup()){
            TelegramManager.getTelegramManager().getSuperGroupInfo(context, chatInfo.superGroupId(), new TgResultBlock<SuperGroupInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo obj) {
                    setSuperGroupInfo(obj);
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
    }

    private Map<Long,String> groupNickNames = new HashMap<>();


    public String getGroupNickNameByUserId(long userId){
        if(groupNickNames.containsKey(userId)){
            return groupNickNames.get(userId);
        }
        return null;
    }

    public void putGroupNickName(long userId,String nickName){
        groupNickNames.put(userId,nickName);
    }




    public void loadGroupMembers(Context context,ChatInfo chatInfo){
        groupNickNames.clear();
        if(chatInfo!=null&&chatInfo.isSuperGroup()){
            TelegramManager.getTelegramManager().getSuperGroupMembers(context,chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterAdministrators", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                    adminMemberInfos = obj;
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
            TelegramManager.getTelegramManager().getSuperGroupMembers(context,chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterRestricted", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                    silenceMemberInfos = obj;

                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
            TelegramManager.getTelegramManager().getSuperGroupMembers(context,chatInfo.id, chatInfo.superGroupId(), null, null, 0, 1000, new TgResultBlock<List<GroupMemberInfo>>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                    groupMemberInfos = obj;
                    int onlineNumber = 0;
                    if(groupMemberInfos!=null&&groupMemberInfos.size()>0){
                        for(GroupMemberInfo iteminfo : groupMemberInfos){
                            if(!TextUtils.isEmpty(iteminfo.nickname)){
                                groupNickNames.put(iteminfo.user_id,iteminfo.nickname);
                            }
                            UserInfo userInfo = UserInfo.getUserInfo(iteminfo.user_id);
                            if (userInfo != null&&userInfo.isOnline()){
                                onlineNumber++;
                            }
                        }
                    }
                    groupSubTitleLiveData().postValue(new Pair<Long, String>(chatInfo.superGroupId(),String.format(App.getInstanse().getString(R.string.number_person_online),onlineNumber)));
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                }
            });
        }
    }

    public void setSuperGroupInfo(SuperGroupInfo groupInfo){
        superGroupInfo = groupInfo;
        groupInfoLiveData().postValue(groupInfo);
    }

    public boolean canEditGroupSetting() {
        if (superGroupInfo != null && superGroupInfo.status != null) {
            switch (superGroupInfo.status.getMemberState()) {
                case GroupMemberState_Administrator:
                    //管理员
                    return true;
                case GroupMemberState_Creator:
                    //创建者
                    if (superGroupInfo.status.is_member) {
                        return true;
                    }
                    break;
                case GroupMemberState_Left:
                    //不在群组
                    break;
                case GroupMemberState_Member:
                    //普通成员
                    break;
                case GroupMemberState_Banned:
                    //被禁用
                    break;
                case GroupMemberState_Restricted:
                    //被禁言
                    break;
                default:
                    break;
            }
        }
        return false;
    }
    public void sendRemotePhoto(ChatInfo conversation,PhotoInfo photoInfo){
        sendRemotePhoto(conversation, photoInfo, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void sendRemotePhoto(ChatInfo conversation, PhotoInfo photoInfo, TgResultBlock<TgResponse> block){
        if(photoInfo==null&&photoInfo.messagePhoto()==null||photoInfo.messagePhoto().photo==null){
            return;
        }
        TelegramManager.getTelegramManager().sendPhotoMessage(ActivityUtils.getTopActivity(),conversation.id, photoInfo.getRemotePhotoFileId()
                , photoInfo.messagePhoto().width, photoInfo.messagePhoto().height
                , getBurnAfterCountDown(),block);
    }
    public void sendVideoMsg(ChatInfo conversation, VideoInfo videoInfo) {
        sendVideoMsg(conversation,videoInfo,new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (obj!=null&&!obj.ok) {
                    showErrorTip(obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    public void sendVideoMsg(ChatInfo conversation, VideoInfo videoInfo, TgResultBlock<TgResponse> block) {
        if(videoInfo==null){
            return;
        }
        if(!canSendMediaMsg(conversation)){
            return;
        }
        TelegramManager.getTelegramManager().sendVideoMessage(ActivityUtils.getTopActivity(),conversation.id, videoInfo.getRemoteVideoFileId()
                , videoInfo.width, videoInfo.height, videoInfo.duration,getBurnAfterCountDown(),block);
    }


    //同步群通知
    public void syncGroupNotice(ChatInfo chatInfo) {
        TelegramManager.getTelegramManager().getGroupNotice(ActivityUtils.getTopActivity(), chatInfo.id, new TgResultBlock<MessageInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, MessageInfo obj) {
                if (obj != null) {
                    if (obj != null) {
                        String text = obj.toString();
                        if (text.startsWith(Constants.GROUP_NOTICE_PREFIX)) {
                            text = text.substring(Constants.GROUP_NOTICE_PREFIX.length());
                        } else if (text.startsWith(Constants.GROUP_NOTICE_PREFIX.trim())) {
                            text = text.substring(Constants.GROUP_NOTICE_PREFIX.trim().length());
                        }
                        announcementTitle.postValue(text);
                    } else {
                        announcementTitle.postValue("");
                    }
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }
}
